import '@/public-path'
import '@/styles/index.scss'

import { createApp } from 'vue'
import App from './App.vue'
import Layout from './layout'
import { routes } from '@/router'
import { setupTDesign } from '@/plugins'
import { setupStore } from '@/stores'
import api from '@/api/path'
import components from '@/components'
import directives from '@/directives/index.js'

import { createRouter, createWebHistory } from 'vue-router'
let app = null
let router = null
// 全局注册API
window['$api'] = api
function render(props = {}) {
  const { container, permissions, appStore, appCommon, routeBase } = props
  app = createApp(window.__POWERED_BY_QIANKUN__ ? App : Layout)

  const history = createWebHistory(
    window.__POWERED_BY_QIANKUN__ || process.env.NODE_ENV === 'production'
      ? `/portal/work-management`
      : '/'
  )
  router = createRouter({
    history,
    routes
  })
  router.beforeEach((to, from, next) => {
    if (!history.state.current) {
      history.state.current = window.location.href.replace(
        `${window.location.origin}${routeBase}`,
        ''
      )
    }
    next()
  })
  // 挂载Tdesign
  setupTDesign(app)
  // 挂载pinia
  setupStore(app)

  appCommon && (window['$outLogin'] = appCommon.outLogin)
  app.config.globalProperties.$appCommon = appCommon
  app.config.globalProperties.$permissions = permissions
  app.config.globalProperties.$myGlobalStore = appStore
  app
    .use(router)
    .use(components)
    .use(directives)
    .mount(container ? container.querySelector('#mirco-app') : '#mirco-app')
}

// 独立运行时
if (!window.__POWERED_BY_QIANKUN__) {
  render()
}

// 接入协议
export async function bootstrap() {
  console.log('vue: bootstrap')
}
export async function mount(props) {
  render(props)
}
export async function unmount() {
  app.unmount()
  app._container.innerHTML = ''
  app = null
  router = null
}
export async function update() {
  // 更新微应用
}
